<template>
    <div class="app-container">

        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
                        <!-- <el-form-item label="开放平台ID" prop="openId">
                            <el-input
                                    v-model="queryParams.openId"
                                    placeholder="请输入开放平台ID"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item> -->
                        <el-form-item label="用户姓名" prop="name">
                            <el-input
                                    v-model="queryParams.name"
                                    placeholder="请输入用户姓名"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="性别" prop="gender">
                            <el-select
                                    v-model="queryParams.gender"
                                    placeholder="请选择性别"
                                    clearable
                                    style="width: 150px"
                            >
                                <el-option
                                    v-for="item in genderOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                            />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="出生日期" prop="birthday">
                            <el-date-picker
                                v-model="dateRange"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                            value-format="YYYY-MM-DD"
                                @change="handleDateRangeChange"
                            />
                        </el-form-item>
                        <el-form-item label="所属学院" prop="college">
                            <el-input
                                    v-model="queryParams.college"
                                    placeholder="请输入所属学院"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="所学专业" prop="major">
                            <el-input
                                    v-model="queryParams.major"
                                    placeholder="请输入所学专业"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item label="年级" prop="grade">
                            <el-input
                                    v-model="queryParams.grade"
                                    placeholder="请输入年级"
                                    clearable
                                    @keyup.enter="handleQuery"
                            />
                        </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['bus:user:add']"
                >新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['bus:user:edit']"
                >修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['bus:user:remove']"
                >删除</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['bus:user:export']"
                >导出</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row> -->
<br>
        <el-table v-loading="loading" :data="userList">
            <el-table-column width="55" align="center" />
                    <!-- <el-table-column label="用户ID" align="center" prop="userId" /> -->
                    <el-table-column label="开放平台ID" align="center" prop="openId" />
                    <el-table-column label="用户姓名" align="center" prop="name" />
                    <el-table-column label="年龄" align="center">
                        <template #default="scope">
                            <span>{{ calculateAge(scope.row.birthday) }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="性别" align="center" prop="gender">
                        <template #default="scope">
                            <el-tag :type="scope.row.gender === 1 ? 'primary' : 'success'" size="small">
                                {{ formatGender(scope.row.gender) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="出生日期" align="center" prop="birthday" width="180">
                        <template #default="scope">
                            <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="所属学院" align="center" prop="college" />
                    <el-table-column label="所学专业" align="center" prop="major" />
                    <el-table-column label="年级" align="center" prop="grade" />
            <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['bus:user:edit']">修改</el-button>
                   <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['bus:user:remove']">删除</el-button> 
                </template>
            </el-table-column> -->
        </el-table>

        <pagination
                v-show="total>0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
        />

        <!-- 添加或修改微信用户信息对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
            <el-form ref="userRef" :model="form" :rules="rules" label-width="80px">
                                <!-- <el-form-item label="开放平台ID" prop="openId">
                                    <el-input v-model="form.openId" placeholder="请输入开放平台ID" />
                                </el-form-item> -->
                                <el-form-item label="用户姓名" prop="name">
                                    <el-input v-model="form.name" placeholder="请输入用户姓名" />
                                </el-form-item>
                                <el-form-item label="出生日期" prop="birthday">
                                    <el-date-picker clearable
                                                    v-model="form.birthday"
                                                    type="date"
                                                    value-format="YYYY-MM-DD"
                                                    placeholder="请选择出生日期">
                                    </el-date-picker>
                                </el-form-item>
                                <el-form-item label="性别" prop="gender">
                                    <el-select v-model="form.gender" placeholder="请选择性别">
                                        <el-option
                                            v-for="item in genderOptions"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value"
                                        />
                                    </el-select>
                                </el-form-item>
                                <el-form-item label="所属学院" prop="college">
                                    <el-input v-model="form.college" placeholder="请输入所属学院" />
                                </el-form-item>
                                <el-form-item label="所学专业" prop="major">
                                    <el-input v-model="form.major" placeholder="请输入所学专业" />
                                </el-form-item>
                                <el-form-item label="年级" prop="grade">
                                    <el-input v-model="form.grade" placeholder="请输入年级" />
                                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="User">
    import { listUser, getUser, delUser, addUser, updateUser } from "@/api/bus/user";

    const { proxy } = getCurrentInstance();
    const { sys_user_sex } = proxy.useDict("sys_user_sex");

    // 自定义性别选项
    const genderOptions = ref([
        { value: 1, label: '男' },
        { value: 2, label: '女' },
        { value: 0, label: '未知' }
    ]);

    // 日期范围
    const dateRange = ref([]);

    // 处理日期范围变化
    function handleDateRangeChange(val) {
        if (val) {
            queryParams.value.beginBirthday = val[0];
            queryParams.value.endBirthday = val[1];
        } else {
            queryParams.value.beginBirthday = undefined;
            queryParams.value.endBirthday = undefined;
        }
    }

    // 计算年龄
    function calculateAge(birthday) {
        if (!birthday) {
            return '--';
        }
        const today = new Date();
        const birthDate = new Date(birthday);
        let age = today.getFullYear() - birthDate.getFullYear();
        const monthDiff = today.getMonth() - birthDate.getMonth();
        
        // 如果今年还没过生日，年龄减1
        if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
            age--;
        }
        
        return age;
    }

    // 格式化性别
    function formatGender(gender) {
        if (gender === 1) {
            return '男';
        } else if (gender === 2) {
            return '女';
        }
        return '未知';
    }

    const userList = ref([]);
    const open = ref(false);
    const loading = ref(true);
    const showSearch = ref(true);
    const ids = ref([]);
    const single = ref(true);
    const multiple = ref(true);
    const total = ref(0);
    const title = ref("");

    const data = reactive({
        form: {},
        queryParams: {
            pageNum: 1,
            pageSize: 10,
                openId: null,
                name: null,
                gender: null,
                beginBirthday: null,
                endBirthday: null,
                college: null,
                major: null,
                grade: null,
    },
    rules: {
    }
    });

    const { queryParams, form, rules } = toRefs(data);

    /** 查询微信用户信息列表 */
    function getList() {
        loading.value = true;
        listUser(queryParams.value).then(response => {
                userList.value = response.rows;
            total.value = response.total;
            loading.value = false;
        });
    }

    // 取消按钮
    function cancel() {
        open.value = false;
        reset();
    }

    // 表单重置
    function reset() {
        form.value = {
                userId: null,
                openId: null,
                name: null,
                age: null,
                gender: null,
                birthday: null,
                college: null,
                major: null,
                grade: null,
                createTime: null,
                updateTime: null
    };
        proxy.resetForm("userRef");
    }

    /** 搜索按钮操作 */
    function handleQuery() {
        // 确保当选择性别为"未知"时，传递值为0
        // 不需要特殊处理，直接使用选择的值
        queryParams.value.pageNum = 1;
        getList();
    }

    /** 重置按钮操作 */
    function resetQuery() {
        dateRange.value = [];
        queryParams.value = {
            pageNum: 1,
            pageSize: 10,
            openId: null,
            name: null,
            gender: null,
            beginBirthday: null,
            endBirthday: null,
            college: null,
            major: null,
            grade: null,
        };
        proxy.resetForm("queryRef");
        handleQuery();
    }

    // 多选框选中数据
    // function handleSelectionChange(selection) {
    //     ids.value = selection.map(item => item.userId);
    //     single.value = selection.length != 1;
    //     multiple.value = !selection.length;
    // }

    /** 新增按钮操作 */
    function handleAdd() {
        reset();
        open.value = true;
        title.value = "添加微信用户信息";
    }

    /** 修改按钮操作 */
    function handleUpdate(row) {
        reset();
        const _userId = row.userId || ids.value
        getUser(_userId).then(response => {
            form.value = response.data;
            open.value = true;
            title.value = "修改微信用户信息";
        });
    }

    /** 提交按钮 */
    function submitForm() {
        proxy.$refs["userRef"].validate(valid => {
            if (valid) {
                if (form.value.userId != null) {
                    updateUser(form.value).then(response => {
                        proxy.$modal.msgSuccess("修改成功");
                        open.value = false;
                        getList();
                    });
                } else {
                    addUser(form.value).then(response => {
                        proxy.$modal.msgSuccess("新增成功");
                        open.value = false;
                        getList();
                    });
                }
            }
        });
    }

    /** 删除按钮操作 */
    function handleDelete(row) {
        const _userIds = row.userId || ids.value;
        proxy.$modal.confirm('是否确认删除微信用户信息编号为"' + _userIds + '"的数据项？').then(function() {
            return delUser(_userIds);
        }).then(() => {
            getList();
            proxy.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    }

    /** 导出按钮操作 */
    function handleExport() {
        proxy.download('bus/user/export', {
            ...queryParams.value
        }, `user_${new Date().getTime()}.xlsx`)
    }

    getList();
</script>